package com.zhongli.devplatform.service.impl.student;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhongli.devplatform.bean.SecurityHelper;
import com.zhongli.devplatform.dto.student.CommitOperationDTO;
import com.zhongli.devplatform.mapper.operation.ReadCommitOperationMapper;
import com.zhongli.devplatform.mapper.operation.ReadOperationMapper;
import com.zhongli.devplatform.mapper.user.ReadUserMapper;
import com.zhongli.devplatform.po.common.ReadCommitOperationPO;
import com.zhongli.devplatform.po.teacher.ReadOperationPO;
import com.zhongli.devplatform.po.user.ReadUserPO;
import com.zhongli.devplatform.service.imp.student.ReadCommitOperationService;
import com.zhongli.devplatform.vo.student.CommitOperationVO;
import com.zhongli.devplatform.bean.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wy
 * @since 2020/8/3
 */
@Service
public class ReadCommitOperationServiceImpl extends ServiceImpl<ReadCommitOperationMapper, ReadCommitOperationPO> implements ReadCommitOperationService {

    @Autowired
    private ReadCommitOperationMapper commitOperationMapper;

    @Autowired
    private ReadOperationMapper operationMapper;

    @Autowired
    private ReadUserMapper userMapper;

    @Override
    public Res getCommitOperation(Integer studentId, Integer operationId) {
        CommitOperationVO commitOperationVO =  commitOperationMapper.getCommitOperation(studentId, operationId);
        return Res.ok(commitOperationVO);
    }

    @Override
    public Res checkOperation(CommitOperationDTO commitOperationDTO) {
        //批改作业
        ReadCommitOperationPO commitOperationPO = commitOperationMapper.selectById(commitOperationDTO.getId());
        commitOperationPO.setStatus(true);
        commitOperationPO.setComment(commitOperationDTO.getComment());
        commitOperationPO.setUpdateUserId(SecurityHelper.getCurrentUserId());
        commitOperationMapper.updateById(commitOperationPO);

        //统计提交的作业数
        int commitCount = commitOperationMapper.countCommit(commitOperationPO.getOperationId());
        //统计学生人数
        int studentCount = userMapper.selectCount(new QueryWrapper<ReadUserPO>().eq("clazz_id", commitOperationDTO.getClazzId()));
        //如果已批改的人数等于班级人数状态变为已批改
        if (commitCount == studentCount){
            ReadOperationPO operationPO = operationMapper.selectById(commitOperationPO.getOperationId());
            operationPO.setStatus(true);
            operationMapper.updateById(operationPO);
        }
        return Res.ok("已批改");
    }

    @Override
    public Res getUnCheckCount(Integer currentUserId) {
        int count = commitOperationMapper.getUnCheckCount(currentUserId);
        return Res.ok(count);
    }
}
